package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

import static com.example.common.StaticName.ROOT_PATH;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${ip}")
    private String ip;
    @Value("${server.port}")
    private String port;
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        long timeMark = System.currentTimeMillis();
        String fileName=file.getOriginalFilename();
        String fileMark = timeMark+"-"+fileName;
        File storeFile = new File(ROOT_PATH+"/"+fileMark);
        if(!storeFile.getParentFile().exists()){
            storeFile.getParentFile().mkdirs();
        }
        file.transferTo(storeFile);
        String url = "http://"+ip+":"+port+"/files/download?fileMark=" + fileMark;
        return Result.success(url);
    }
    @GetMapping("/download")
    public void download(String fileMark, HttpServletResponse response) throws IOException {
        File file = new File(ROOT_PATH+"/"+fileMark);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileMark, "UTF-8"));
        response.setContentType("application/octet-stream");
        outputStream.write(FileUtil.readBytes(file));
        outputStream.flush();
        outputStream.close();
    }

}
